<template>
	<hyb-page title="编辑信息">
		<template v-slot:body>
			<form @submit="submit">
				<view :style="{'background':$store.state.base.qjcolor}"
					class="gui-padding gui-flex gui-justify-content-center gui-column gui-align-items-center">
					<!-- #ifdef MP -->
					<button type="default" open-type="chooseAvatar" plain @chooseavatar="onChooseAvatar"
						class="gui-button gui-noborder">
						<image style="height: 160rpx;width: 160rpx;border-radius: 50%;" class="gui-flex1"
							:src="userinfo.u_thumb || $store.state.base.erweima" mode="widthFix"></image>

					</button>


					<!-- #endif -->

					<!-- #ifndef MP -->
					<gui-image borderRadius="50%" @click="chooseThumb()" :width="160" :height="160"
						:src="userinfo.u_thumb || $store.state.base.erweima" mode="widthFix">
					</gui-image>
					<!-- #endif -->
					<text class="gui-text-small gui-color-white gui-underline">点击更换</text>
				</view>

				<view class="gui-bg-white gui-dark-bg-level-3 gui-padding-x gui-margin-top">
					<!-- <view class="gui-form-item gui-border-b">
						<text class="gui-form-label gui-secondary-text">用户ID</text>
						<view class="gui-form-body">
							<input type="text" class="gui-form-input" disabled v-model="formData.u_id"
								placeholder="请输入内容" />
						</view>
					</view> -->
					<view class="gui-form-item gui-border-b gui-margin-top">
						<text class="gui-form-label gui-secondary-text">用户id</text>
						<view class="gui-form-body">
							<input type="text" disabled class="gui-form-input" v-model="formData.u_id" name="u_id"
								placeholder="用户id" />
						</view>
					</view>
					<view v-if="userinfo.qy_rz == 3" class="gui-form-item gui-border-b gui-margin-top">
						<text class="gui-form-label gui-secondary-text">未结算款项</text>
						<view class="gui-form-body gui-flex gui-space-between gui-align-items-center">
							<input type="text" disabled class="gui-form-input" v-model="formData.wjs_money"
								name="wjs_money" />


							<hyb-price v-if="userinfo.wjs_money > 0" @comfirm="comfirm" placeholder="结算金额"
								title="结算确认"></hyb-price>

							<!-- <button type="default" @tap="comfirm" style="margin: 0;" class="gui-button-mini gui-bg-red gui-color-white">
									结算确认
								</button> -->
						</view>
					</view>

					<view class="gui-form-item gui-border-b gui-margin-top">
						<text class="gui-form-label gui-secondary-text">用户昵称</text>
						<view class="gui-form-body gui-flex gui-space-between">
							<input type="nickname" class="gui-form-input" v-model="formData.u_name" name="u_name"
								placeholder="请输入用户昵称" />
						</view>
					</view>

					<view class="gui-form-item gui-border-b gui-margin-top">
						<text class="gui-form-label gui-secondary-text">手机号码</text>
						<view class="gui-form-body">
							<hyb-phone v-model="formData.u_phone"></hyb-phone>
							<!-- <input type="text" disabled class="gui-form-input"  name="u_phone"
								placeholder="手机号码" /> -->
						</view>
					</view>

					<view v-if="base.sheng_ri == 1" class="gui-form-item gui-border-b gui-margin-top">
						<text class="gui-form-label gui-secondary-text">生日</text>
						<view class="gui-form-body">
							<hyb-time-selector v-model="formData.u_birthday"></hyb-time-selector>
						</view>
					</view>
					<view v-if="tag == 'qy'">
						<view class="gui-form-item gui-border-b gui-margin-top">
							<text class="gui-form-label gui-secondary-text">单位名称</text>
							<view class="gui-form-body">
								<input type="text" class="gui-form-input" v-model="formData.u_department" name="u_name"
									placeholder="请输入单位名称" />
							</view>
						</view>
						<view class="gui-form-item gui-border-b gui-margin-top">
							<text class="gui-form-label gui-secondary-text">纳税人识别号</text>
							<view class="gui-form-body">
								<input type="text" class="gui-form-input" v-model="formData.shui_hao" name="u_name"
									placeholder="请输入纳税人识别号" />
							</view>
						</view>
						<view class="gui-form-item gui-border-b gui-margin-top">
							<text class="gui-form-label gui-secondary-text">开票备注</text>
							<view class="gui-form-body">
								<input type="text" class="gui-form-input" v-model="formData.fa_piao_beizhu"
									name="u_name" placeholder="请输入开票备注信息" />
							</view>
						</view>
						<view class="gui-form-item gui-border-b gui-margin-top">
							<text class="gui-form-label gui-secondary-text">单位地址</text>
							<view class="gui-form-body">
								<input type="text" class="gui-form-input" v-model="formData.u_address" name="u_name"
									placeholder="请输入单位地址" />
							</view>
						</view>
					</view>

					<view v-if="base.denglu_fangshi == 1 || base.denglu_fangshi == 4"
						class="gui-form-item gui-border-b gui-margin-top">
						<text class="gui-form-label gui-secondary-text">登录密码</text>
						<view class="gui-form-body">
							<input type="password" class="gui-form-input" v-if="isPwd" v-model="formData.passwd"
								name="name3" placeholder="请输入密码" />
							<input type="text" class="gui-form-input" v-if="!isPwd" :disabled="true"
								v-model="formData.passwd" name="name3" placeholder="请输入密码" />
						</view>
						<text class="gui-form-icon gui-icons gui-text-center"
							:class="[!isPwd ? 'gui-primary-color' : 'gui-color-gray']"
							@tap="isPwd=!isPwd">&#xe609;</text>
					</view>


					<!-- <view class="gui-form-item gui-border-b gui-margin-top">
						<text class="gui-form-label">性别</text>
						<view class="gui-form-body">
							<picker mode="selector" :range="gender" @change="sexChange">
								<view class="gui-flex gui-row gui-nowrap gui-space-between gui-align-items-center">
									<text class="gui-text gui-secondary-text">{{gender[genderIndex]}}</text>
									<text class="gui-form-icon gui-icons gui-text-center gui-color-gray">&#xe603;</text>
								</view>
							</picker>
						</view>
					</view> -->
				</view>

				<view class="gui-dark-bg-level-3 gui-padding gui-margin-top">
					<gui-radio @change="privacyChange" :checked="checked" v-model="checked">
						已阅读并同意 <text class="gui-primary-color" @tap.stop="privacy()">《用户协议与隐私》</text>
					</gui-radio>
				</view>

				<view class="gui-margin-top gui-padding">
					<button type="default" class="gui-button gui-bg-primary gui-noborder" @tap="save"
						style="border-radius:50rpx;">
						<text class="gui-color-white gui-button-text">保 存</text>
					</button>
				</view>
			</form>

			<hyb-privacy ref="privacy" :content="base.xieyi" @change="privacyChange" v-model="checked"></hyb-privacy>
		</template>
	</hyb-page>
</template>

<script>
	export default {
		data() {
			return {
				checked: false,
				passwd: '',
				isPwd: true,
				userinfo: {},
				gender: ['男', '女'],
				genderIndex: 0,
				formData: {}
			}
		},
		computed: {
			base: function() {
				return uni.storage.get("base");
			}
		},

		onLoad(options) {

			this.tag = options.tag; //获取企业标识
			this.userinfo = uni.storage.get("userinfo");
			this.genderIndex = this.userinfo.sex;
			this.formData = {
				passwd: "",
				u_id: this.userinfo.u_id,
				wjs_money: this.userinfo.wjs_money,
				u_name: this.userinfo.u_name,
				sex: this.userinfo.sex,
				u_phone: this.userinfo.u_phone,
				u_birthday: this.userinfo.u_birthday
			};
		},
		methods: {
			privacy() {
				this.$refs.privacy.open()
			},

			privacyChange(val) {
				this.checked = val;
			},

			comfirm(data, money) {

				if (!this.checked) {
					uni.showToast({
						title: '请先同意用户协议',
						icon: 'none'
					})
					return
				}

				if (parseInt(money) > this.userinfo.wjs_money) {
					uni.showToast({
						title: "结算金额不能超过" + this.userinfo.wjs_money + "元",
						icon: "none"
					})
					return;
				}

				uni.gPost("user/jiesuan", {
					money: money
				}).then((userinfo) => {
					uni.storage.set("userinfo", userinfo);
					this.formData.wjs_money = userinfo.wjs_money;
					uni.showToast({
						title: "操作成功!"
					});
				})
			},


			onChooseAvatar(e) {
				console.log(e)
				let avatarUrl = e.detail.avatarUrl;
				let file = {
					name: avatarUrl,
					url: avatarUrl
				};
				this.upload(file).then((url) => {
					uni.gPost("user/save", {
						u_id: this.userinfo.u_id,
						u_thumb: url
					}).then((userinfo) => {
						this.userinfo = userinfo;
						this.$store.commit("set_user", userinfo)
						uni.storage.set("userinfo", userinfo);
						uni.showToast({
							title: "保存成功!"
						});
					})
				})
			},

			chooseThumb() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						console.log(res)
						this.upload({
							name: res.tempFiles[0].name || res.tempFiles[0].path,
							url: res.tempFilePaths[0]
						}).then((url) => {
							uni.gPost("user/save", {
								u_id: this.userinfo.u_id,
								u_thumb: url
							}).then((userinfo) => {
								this.userinfo = userinfo;
								this.$store.commit("set_user", userinfo)
								uni.storage.set("userinfo", userinfo);
								uni.showToast({
									title: "保存成功!"
								});
							})
						})
					},
					complete: function() {}
				});
			},



			upload(file) {
				return new Promise((resolve) => {
					let lastIndex = file.name.lastIndexOf('.');
					let ext = lastIndex > -1 ? file.name.slice(lastIndex + 1) : '';
					this.getUploadInfo(ext).then((info) => {
						info.filePath = file.url;
						this.uploadFile(info).then((url) => {
							resolve(url);
						})
					})
				})
			},

			getUploadInfo(ext) {
				// 传入文件后缀，让后端生成随机的 COS 对象路径，并返回上传域名、PostObject 接口要用的 policy 签名
				// 参考服务端示例：https://github.com/tencentyun/cos-demo/server/post-policy/
				return new Promise((resolve) => {
					let now = Math.round(Date.now() / 1000);
					let exp = now + 900;
					let expiration = new Date(exp * 1000).toISOString();
					uni.gPost("policy", {
						now: now,
						exp: exp,
						expiration: expiration,
						ext: ext
					}).then((data) => {
						resolve(data)
					})
				})
			},

			uploadFile(opt) {
				return new Promise((resolve, reject) => {
					var formData = {
						key: opt.cosKey,
						policy: opt.policy, // 这个传 policy 的 base64 字符串
						success_action_status: 200,
						'q-sign-algorithm': opt.qSignAlgorithm,
						'q-ak': opt.qAk,
						'q-key-time': opt.qKeyTime,
						'q-signature': opt.qSignature,
					};
					// 如果服务端用了临时密钥计算，需要传 x-cos-security-token
					if (opt.securityToken) formData['x-cos-security-token'] = formData.securityToken;
					uni.uploadFile({
						url: 'https://' + opt.cosHost, //仅为示例，非真实的接口地址
						filePath: opt.filePath,
						name: 'file',
						formData: formData,
						success: (res) => {
							console.log(res)
							if (![200, 204].includes(res.statusCode)) reject(res);
							var fileUrl = 'https://' + opt.cosHost + '/' + opt.cosKey
								.replace(/%2F/g, '/');
							resolve(fileUrl);
						},
						error(err) {
							reject(err)
						},
					});
				});

			},

			sexChange(e) {
				this.formData.sex = e.detail.value;
			},
			save() {

				if (!this.checked) {
					uni.showToast({
						title: '请先同意用户协议',
						icon: 'none'
					})
					return
				}

				if (this.tag == 'qy' && this.userinfo.qy_rz != 3) {
					this.formData.qy_rz = 1;
				}

				uni.gPost("user/save", this.formData).then((userinfo) => {
					this.$store.commit("set_user", userinfo)
					uni.storage.set("userinfo", userinfo);
					uni.showToast({
						title: "保存成功!"
					});
					uni.navigateTo({
						url: this.$store.state.base.hyzx_luj
					})
				})
			}
		}
	}
</script>

<style>

</style>